<template>
  <div>
    <div class="add">
      <a-button type="primary" @click="addAddress">新增</a-button>
    </div>
    <PickTablePage
      ref="tablePageRef"
      :api-params="apiParams"
      :columns="columnsAddressTable"
      :api="getMemberAddressData"
      :methods="sortMethods"
      @deleteAddress="handleMemberDetails"
      @editAddress="editHandleMemberDetails"
    >
    </PickTablePage>
    <a-modal v-model:visible="visible" :width="700">
      <template #title> {{ form.id ? '修改' : '新增' }}会员地址 </template>
      <a-form
        ref="formRef"
        :model="form"
        :style="{ width: '460px' }"
        layout="horizontal"
        auto-label-width
      >
        <a-form-item
          field="name"
          label="收货人姓名"
          :rules="[REQUIRED, VARCHAR20]"
        >
          <a-input v-model="form.name" />
        </a-form-item>
        <a-form-item
          field="mobile"
          label="收货人手机"
          :rules="[REQUIRED, MOBILE]"
        >
          <a-input v-model="form.mobile"  :max-length="11" />
        </a-form-item>
        <a-form-item field="consigneeAddressPath" label="收货人地址">
          <PickChoiceCity :api="getChildRegion" :key="isShowCity"  @callback="cityRes" :ids="form.consigneeAddressIdPath" :address="form.consigneeAddressPath" ></PickChoiceCity>
        </a-form-item>
        <a-form-item field="detail" label="详细地址" :rules="[REQUIRED]">
          <a-input v-model="form.detail" />
        </a-form-item>
        <a-form-item field="alias" label="地址别名">
          <a-input v-model="form.alias" />
        </a-form-item>
        <a-form-item label="默认">
          <a-radio-group v-model="form.isDefault" type="button">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
      <template #footer>
        <div style="text-align: right">
          <a-button @click="handleCancel">取消</a-button>
          <a-button
            style="margin-left: 10px"
            type="primary"
            @click="handleOk"
            >保存</a-button
          >
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { PickTablePage, PickChoiceCity } from '@pickmall/ui-v3-components'  
  import { getChildRegion } from '@/api/common';
  import { useRoute } from 'vue-router';
  import {
    getMemberAddressData,
    addMemberAddress,
    editMemberAddress,
    removeMemberAddress,
  } from '@/api/member';
  import { ColumnsDataRule, MethodsRule } from '@/types/global';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { Message } from '@arco-design/web-vue';
  import { VARCHAR20, REQUIRED, MOBILE } from '@/utils/validator';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { whetherDefault } from '@/utils/tools';
  import { addressRule } from './type';

  const isShowCity = ref(1);
  const formRef = ref<any>(); // 表单
  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const tablePageRef = ref<any>();
  const visible = ref(false);
  const route = useRoute();
  const memberId = ref<any>('');
  const form = ref<addressRule>({
    name: '',
    isDefault: false,
    alias: '',
    detail: '',
    consigneeAddressPath: '',
    mobile: '',
    center: '',
    id: '',
    consigneeAddressIdPath:'',
  });
  // 初始化
  onMounted(() => {
    memberId.value = route.query.id as any;
  });

  // TA收货地址
  const columnsAddressTable: ColumnsDataRule[] = [
    {
      title: '地址别名',
      dataIndex: 'alias',
    },
    {
      title: '收货人姓名',
      dataIndex: 'name',
    },
    {
      title: '收货人电话',
      dataIndex: 'mobile',
    },
    {
      title: '地址',
      dataIndex: 'consigneeAddressPath',
    },
    {
      title: '详细地址',
      dataIndex: 'detail',
    },
    {
      title: '默认',
      dataIndex: 'isDefault',
      slot: true,
      slotData: {
        tag: whetherDefault,
      },
    },
  ];
  // 传递的参数
  const apiParams = {
    memberId: route.query.id as any,
  };
  // 新增
  const addAddress = () => {  
    isShowCity.value = 1;
    formRef.value.resetFields(); // 清空表单
    // Object.keys(form.value).forEach((key) => {
    //   form.value[key] = '';
    // });
    form.value.isDefault = false
    delete form.value.id;
    visible.value = true;
  };
  // 级联传过来的值
  const cityRes = (val: any) => {
    form.value.consigneeAddressPath = val.cities.join(',');
    form.value.consigneeAddressIdPath = val.ids.join(',');
  };
  // 编辑
  const editHandleMemberDetails = (v: any) => {
    isShowCity.value += 1;
    if (v) {
      Object.keys(v.record).forEach((key) => {
        // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
        form.value.hasOwnProperty(key)  ? (form.value[key] = v.record[key]) : '';
      });
      form.value.id = v.record.id;
    }
    visible.value = true;
  };
  const handleOk = async () => {
    const auth = await formRef.value?.validate();
    if (!auth) {
      const submit = JSON.parse(JSON.stringify(form.value));
      const params = {
        ...submit,
        memberId: memberId.value ?? ''
      };
      const result = submit.id
        ? await editMemberAddress(params)
        : await addMemberAddress(params);
      if (result.data.code == 200) {
        Message.success(`${submit.id ? '修改' : '新增'}成功`);
        tablePageRef.value.init();
        visible.value = false;
      }
    }
  };
  const handleCancel = () => {
    visible.value = false;
  };
  // 操作列表
  const sortMethods: MethodsRule = {
    title: '操作',
    width: 200,
    fixed: 'right',
    methods: [
      {
        title: '删除',
        callback: 'deleteAddress',
      },
      {
        title: '编辑',
        callback: 'editAddress',
      },
    ],
  };
  // 删除
  const handleMemberDetails = (val: any) => {
    modal.confirm({
      title: '删除',
      content: '确定要删除此收货地址？',
      alignCenter: false,
      onOk: async () => {
        const res = await removeMemberAddress(val.record.id);
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  };
</script>

<style lang="less" scoped>
  .add {
    margin-bottom: 20px;
  }
</style>
